<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>内容分类管理</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://static.talkyun.com/frame/layui/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="https://static.talkyun.com/frame/layui/style/skin/default.css" media="all">
    <link rel="stylesheet" href="../css/style.css" media="all">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/common.js"></script>
    <script src="../layui/layui.js"></script>
    <script src="../js/api.js"></script>
    <script src="index.js"></script>
</head>

<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>内容分类管理</legend>
</fieldset>
<form class="layui-form" action="">
    <div class="layui-form-item">
        <div class="layui-inline">
            <div class="layui-input-inline">
                <button type="submit" class="layui-btn" id="demoSelect1" lay-filter="demoSelect1">查询</button>
            </div>
        </div>
    </div>
</form>


<table class="layui-hide" id="test" lay-filter="testevent"></table>

<!--    模板scripty-->
<script type="text/html" id="barDemo">
    <!--<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>-->
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!--    弹出窗的模板-->
<script type="text/html" id="argSchemaTemplate">
    <form class="layui-form" action="">
        <div class="layui-input-block" hidden>
            <input class="layui-input" type="text" name="id" value="{{d.id}}" autocomplete="off" placeholder="请输入id" />
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">上级分类</label>
            <div class="layui-input-inline">
                <select name="parentId" id="parentId">
                        <option value="0">一级目录</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">分类名称</label>
            <div class="layui-input-inline">
                    <input class="layui-input" type="text" name="name" value="{{d.name}}" autocomplete="off" placeholder="请输入分类名称" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">跳转URL</label>
            <div class="layui-input-inline">
                    <input class="layui-input" type="text" name="url" value="{{d.url}}" autocomplete="off" placeholder="请输入跳转URL" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1">提交</button>
        </div>
    </form>

</script>
<script type="text/javascript">
    layuiModules = ['table', 'form', 'laydate', 'admin'];
    function mounted() {
        var form = layui.form
            , layer = layui.layer
            , laydate = layui.laydate;
        var table = layui.table;
        var $ = layui.$;
        var api = layui.api;
        var admin = layui.admin;

        var where = {
            pageNo: 1,
            pageSize: 20
        };

        table.render({
            elem: '#test'
            , url: api.category.all
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            , page: false
            , contentType: "application/json"
            , parseData: function (res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.data.totalSize,
                    "data": res.data.result
                }
            }
            , done: function (res, curr, count) {
                // loadPage(curr, count);
            }
            , cols: [[
                { field: 'name', width: 180, title: '分类名称' }
                , { field: 'parentName', width: 180, title: '上级分类名称' }
                , { field: 'url', width: 180, title: '跳转URL' }
                , { fixed: 'right', width: 165, align: 'center', toolbar: '#barDemo' }
            ]]
            , where: where

        });

        form.render();
       
        //新增和编辑同一个  试一试
        function addItem(data) {
            admin.req({
                url: api.category.add,
                data: data.field,
                async: false,
                success: function (res) {
                    layer.msg('新增成功');
                    layer.closeAll();
                    table.reload('test', { where: where });
                }
            });
        }

        function updateItem(data) {
            admin.req({
                url: api.category.update,
                data: data.field,
                async: false,
                success: function (res) {
                    layer.msg('修改成功');
                    layer.closeAll();
                    table.reload('test', { where: where });
                }
            });
        }

        //监听提交
        form.on('submit(demo1)', function (data) {
            if (data.field.id && data.field.id != 'undefined' && data.field.id != '') {
                data.field.parentName = $("#parentId").find("option:selected").text();
                updateItem(data);
            } else {
                data.field.id =0;
                data.field.parentName = $("#parentId").find("option:selected").text();
                addItem(data);
            }
            return false;
        });

        $('#demoSelect1').click(function () {
            layui.table.reload('test', { where: where });
        });

        //监听头工具栏事件
        table.on('toolbar(testevent)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id)
                , data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    openlayer({ platform: "", position: "" });
                    break;
                case 'update':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        // layer.alert('编辑 [id]：' + checkStatus.data[0].id);
                        // layer.alert('data string:' + JSON.stringify(data));
                        openlayer(data[0]);
                        // addItem(data);
                    }
                    break;
                case 'delete':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        layer.msg('删除');
                    }
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(testevent)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'detail') {
                layer.msg('查看操作');
                layui.data('qw_advert_id', {
                    key: 'adId',
                    value: data.id
                });
                var parents = parent.parent;
                var content1 = 'html/advertmanager.html';
                parents.layer.open({
                    type: 2,
                    // title: '查看详情',
                    shade: 0.6,
                    area: ['1000px', '660px'],
                    maxmin: false,
                    content: content1,
                    zIndex: layer.zIndex,
                    success: function (layero) {
                        // layer.setTop(layero);
                    }
                });
            } else if (layEvent === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    layer.close(index);
                    admin.req({
                        url: `${api.category.delete}?id=${obj.data.id}`,
                        contentType: 'application/x-www-form-urlencoded',
                        async: false,
                        success: function (res) {
                            layer.msg('删除成功')
                            table.reload('test', { where: where });
                        }
                    });
                });
            } else if (layEvent === 'edit') {
                layer.msg('编辑操作');
                openlayer(data)
            }
        });
      
        function openlayer(data, index) {
            var templet = $('#argSchemaTemplate').html();
            layui.laytpl(templet).render(data, function (html) {
                //layer 弹出窗
                //在这里面输入任何合法的js语句
                index = layer.open({
                    type: 1 //Page层类型
                    , area: ['500px', '300px']
                    , title: '添加'
                    , shade: 0.6 //遮罩透明度
                    , maxmin: false //允许全屏最小化
                    , anim: -1 //0-6的动画形式，-1不开启
                    , content: html,
                    success: function (layero, index) {
                        // todo 加载下拉框的值
                        admin.req({
                            url: api.category.list,
                            contentType: 'application/json',
                            async: false,
                            success: function (res) {
                                $.each(res, function (i, v) {
                                    var id = v.id;
                                    var text = v.name;
                                    var secondName = v.parentName;
                                    if(!secondName || secondName=='undefined'){
                                        secondName ="";
                                    }else{
                                        secondName =  secondName+"/"
                                    }
                                    console.log(text);
                                    $("#parentId").append("<option value='" + id + "'>" +secondName + text + "</option>");
                                });
                            }
                        });
                        console.log(data)
                        if(data.parentId && data.parentId>0){
                            $("#parentId").val(data.parentId)
                        }
                        form.render();
                    }
                });
            });
        }
    };
</script>
</body>

</html>